/*
 * Created on Feb 15, 2005
 * Created by dfhuynh
 */
package it.okkam.longwell.ui.command;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;

import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.tdb.TDBFactory;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.LongwellServlet;
import edu.mit.simile.longwell.Profile;
import edu.mit.simile.longwell.schema.IStructuredSchema;
import edu.mit.simile.longwell.ui.Facade;
import edu.mit.simile.longwell.ui.FlairMessage;
import edu.mit.simile.longwell.ui.FlairStructuredModel;
import edu.mit.simile.longwell.ui.InjectionManager;
import edu.mit.simile.longwell.ui.command.CommandBase;

/**
 * @author dfhuynh
 */
public class SelectDatasetAdministrationCommand extends CommandBase {
	final static private Logger s_logger = Logger.getLogger(SelectDatasetAdministrationCommand.class);

	final protected String m_template;
	private File[] m_filesComuni;
	/**
	 * @param injectionManager
	 */
	public SelectDatasetAdministrationCommand(InjectionManager injectionManager, String template) {
		super(injectionManager);
		m_template = template;

	}
	public SelectDatasetAdministrationCommand(InjectionManager injectionManager,File[] filesComuni, String template) {
		super(injectionManager);
		m_template = template;
		m_filesComuni=filesComuni;
	}
	/* (non-Javadoc)
	 * @see edu.mit.simile.flair.IFlairCommand#execute(edu.mit.simile.flair.FlairMessage)
	 */
	public void execute(FlairMessage msg) throws ServletException {
		try {
			VelocityContext vcContext = createContext(msg);
			HttpSession session = msg.m_request.getSession();
			String sessionId = msg.m_request.getSession().getId();
			String[] grafiSelezionati =(String[]) session.getAttribute("graphName");
			String username = (String) session.getAttribute(sessionId+"username");
			if(grafiSelezionati!=null && grafiSelezionati.length>0){
				String assemblerFile = SetDatasetCommand.getListaComuni()[0]+"-assembler.ttl";
				//String assemblerFile = session.getAttribute("listaComuni").toString()+".ttl";
				System.out.println("assemblerFile "+assemblerFile);
				Dataset ds = TDBFactory.assembleDataset(LongwellServlet.getAssemblerDirectory()+"/"+assemblerFile);		
				
				for(int i = 0; i<grafiSelezionati.length; i++){
					msg.getProfileFromSession().removeData(ds.getNamedModel(grafiSelezionati[i]));
				}
				System.out.println("Grafi selezionati: "+grafiSelezionati.length);
				s_logger.info("elimino il modello in quanto gia' presente");
			}
			vcContext.put("comuni", getComuni());
			vcContext.put("username", username);
			msg.m_ve.mergeTemplate(
				m_template,
				vcContext,
				msg.m_response.getWriter());
		} catch (Exception e) {
			s_logger.error(e);
			e.printStackTrace();
		}
	}

	protected Set getGraphs(FlairMessage msg) {
		SortedSet sGraphs = new TreeSet();
		ArrayList<Dataset> datasets = new ArrayList<Dataset>();
		datasets = LongwellServlet.m_dataset;
		s_logger.info("Find " + datasets.size()+" datasets");
		for (int i=0; i<datasets.size();i++){
			Dataset ds = datasets.get(i);
			Iterator<String> graphNames = ds.listNames();
			while (graphNames.hasNext()) {
			    String graphName = graphNames.next();
			    System.out.println(graphName);
			    sGraphs.add(graphName);
			}			
		}
		return sGraphs;
	}
	protected Set  getComuni(){
		SortedSet sComuni = new TreeSet();
		for (int i = 0; i < m_filesComuni.length; i++) {
			File file = m_filesComuni[i];
			int index = file.getName().lastIndexOf("-assembler");
		      if (index>0&& index <= file.getName().length() - 2 ) {
		    	  String assemblerFile = file.getName().substring(0, index);
		    	  //hide the dataset used for configuration
		    	  if(!assemblerFile.equals("bcc-utenti")){
		    		  sComuni.add(assemblerFile);
		    	  }
		      }  
		}
		return sComuni;
	}
}
